import { defineStore } from 'pinia'
import { getInfoType, getSourceTypeApi } from '@/apis/order.js'
import { SentimentLevelList, WorkerOrderStatus } from '@/utils/config.js'
import { TimeoutStatusOptions } from '@/common/index.js'

export const useCommonTypesStore = defineStore('commonType', () => {
  const state = reactive({
    infoType: [],
    infoTypeMap: {},
    infoLevel: SentimentLevelList,
    timeoutData: TimeoutStatusOptions,
    sourceType: [],
    sourceTypeMap: {},
    workerOrderStatus: WorkerOrderStatus,
    workerOrderStatusMap: {},
    areaCodeList: [],
    officeIdList: [],
    directUnitIdList: []
  })

  function updateValue(name, val, label = 'label', value = 'value') {
    if (state[name]) {
      state[name] = val
      const curMap = {}
      val.map((item) => {
        return (curMap[item[value]] = item[label])
      })
      state[name + 'Map'] = curMap
    }
  }

  async function init() {
    if (!state.infoType.length) {
      try {
        const res = await getInfoType()
        let { ret, data } = res
        if (ret === 0) {
          updateValue('infoType', data, 'dictLabel', 'dictValue')
        }
      } catch (error) {
        /* empty */
      }
    }
    if (!state.sourceType.length) {
      try {
        const res = await getSourceTypeApi()
        let { ret, data } = res
        if (ret === 0) {
          updateValue('sourceType', data, 'dictLabel', 'dictValue')
        }
      } catch (error) {
        /* empty */
      }
    }
    if (!Object.keys(state.workerOrderStatusMap).length) {
      updateValue('workerOrderStatus', state.workerOrderStatus)
    }
  }

  init().then()
  return {
    state,
    updateValue
  }
})
